/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-15 Time: 23:16
 *
 * 新建服务工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
    TextInput,
    Image, ToastAndroid, Modal
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './addCheckUnusualScreen.Style';
import {
    COLOR_GRAY_LINE,
    COLOR_THEME, COLOR_WHITE, FONT_COLOR_SUB_TITLE,
    FONT_COLOR_TITLE, FONT_SIZE_TITLE
} from "../../../constant/PHColors"
import DividingLineViewComponent from "../../../component/DividingLineViewComponent/DividingLineViewComponent"
import AntDesign from "react-native-vector-icons/AntDesign";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import {save_checkmsg} from "./Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";

Text.defaultProps = Object.assign({}, Text.defaultProps, {allowFontScaling: false});
TextInput.defaultProps = Object.assign({}, TextInput.defaultProps, {defaultProps: false});

class addCheckUnusualScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '选择查房结果',
        headerRight: (
            <TouchableOpacity activeOpacity={0.9} onPress={navigation.getParam('submitClick')}>
                <View style={{ height: 44,paddingRight:15, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center'}}>
                    <Text style={{fontSize: 18, color: navigation.getParam('btnColor')}}>
                        完成
                    </Text>
                </View>
            </TouchableOpacity>
        )
    })

    // 构造
    constructor(props) {
        super(props);

        // 初始状态
        this.state = {
            place: this.props.navigation.getParam("place"),
            orderpid: this.props.navigation.getParam("orderpid"),
            gno: this.props.navigation.getParam("gno"),
            consume:{},     //消费  例：{"001.01":{"name":"衣服","num":3}}
            leave:{},     //遗留  例：{"衣服":"3"}
            roomState:{},     //客房状态  例：{"衣服":"3"}
            changeNumModal:false,   //修改数量
            selectedItem:{"code":"","name":"","num":""},
            imageArr:[{},{},{},{},{},{},{},{},{}], //图片数组
            remark:'',
            btnColor:'#212121',
        };

    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onCheckUnusual !== this.props.onCheckUnusual && nextProps.onCheckUnusual.fetchStatus === FetchStatus.Success) {

            if (nextProps.onCheckUnusual.RETURN === ReturnStatus.Success) {
                ToastAndroid.show(nextProps.onCheckUnusual.MSG, 500);//提示
                this.setState({
                    btnColor:'#212121',
                })
                this.props.navigation.navigate('RoomStatusScreen');
                this.props.navigation.state.params.callBack()
            } else {
                this.setState({
                    btnColor:'#212121',
                })
                dispatch(doDisplayWarnMessage(nextProps.onCheckUnusual.MSG))
            }
        }

    }

    componentWillMount() {
        this.props.navigation.setParams({submitClick: this._submitClick,btnColor:this.state.btnColor});
    }

    render(){
        let _this = this;
        return (
            <SafeAreaView style={styles.body}>
                <ScrollView style={styles.body}>

                    <DividingLineViewComponent lineHeight={10}/>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        this.props.navigation.navigate('chooseConsumeScreen',{consume:_this.state.consume,page:'addCheckUnusualScreen',goBack:(returnJson)=>{
                                _this.setState({
                                    consume:returnJson
                                })
                            }});
                    }}>
                        <View style={{flexDirection:'row',height:50}}>
                            <View style={styles.itemHeaderLeft}>
                                <FontAwesome name={'hourglass-2'} size={20} style={{color: FONT_COLOR_SUB_TITLE,marginLeft: 15,marginRight: 15}}/>
                                <Text style={styles.itemHeaderLeftText}>
                                    消费
                                </Text>
                            </View>
                            <View style={styles.itemHeaderRight}>
                                <View style={styles.itemHeaderRightBox}>
                                    <Text style={styles.itemHeaderRightText}>
                                        添加
                                    </Text>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                    {
                        (JSON.stringify(this.state.consume)!=='{}')&&
                        (
                            this._render_consume()
                        )
                    }

                    <DividingLineViewComponent lineHeight={10}/>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        this.props.navigation.navigate('chooseLeaveScreen',{leave:_this.state.leave,page:'addCheckUnusualScreen',goBack:(returnJson)=>{
                                _this.setState({
                                    leave:returnJson
                                })
                            }});
                    }}>
                        <View style={{flexDirection:'row',height:50}}>
                            <View style={styles.itemHeaderLeft}>
                                <FontAwesome name={'suitcase'} size={20} style={{color: FONT_COLOR_SUB_TITLE,marginLeft: 15,marginRight: 15}}/>
                                <Text style={styles.itemHeaderLeftText}>
                                    遗留
                                </Text>
                            </View>
                            <View style={styles.itemHeaderRight}>
                                <View style={styles.itemHeaderRightBox}>
                                    <Text style={styles.itemHeaderRightText}>
                                        添加
                                    </Text>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                    {
                        (JSON.stringify(this.state.leave)!=='{}')&&
                        (
                            this._render_leave()
                        )
                    }

                    <DividingLineViewComponent lineHeight={10}/>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        this.props.navigation.navigate('chooseRoomStateScreen',{roomState:_this.state.roomState,page:'addCheckUnusualScreen',goBack:(returnJson)=>{
                                _this.setState({
                                    roomState:returnJson
                                })
                            }});
                    }}>
                        <View style={{flexDirection:'row',height:50}}>
                            <View style={styles.itemHeaderLeft}>
                                <FontAwesome name={'hourglass-2'} size={20} style={{color: FONT_COLOR_SUB_TITLE,marginLeft: 15,marginRight: 15}}/>
                                <Text style={styles.itemHeaderLeftText}>
                                    客房状态
                                </Text>
                            </View>
                            <View style={styles.itemHeaderRight}>
                                <View style={styles.itemHeaderRightBox}>
                                    <Text style={styles.itemHeaderRightText}>
                                        添加
                                    </Text>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                    {
                        (JSON.stringify(this.state.roomState)!=='{}')&&
                        (
                            this._render_roomState()
                        )
                    }

                    <DividingLineViewComponent lineHeight={10}/>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        // console.log(JSON.stringify(this.state.imageArr))
                        let _t=this;
                        this.props.navigation.navigate('RepairWorkOrderUploadImageBase64Screen',{"imageArr":this.state.imageArr,goBack:(data)=>{
                                // console.log("--------"+JSON.stringify(data))
                                _t.props.navigation.navigate('addCheckUnusualScreen');
                                _t.setState({
                                    imageArr:data
                                });
                            }})
                    }}>
                        <View style={{flexDirection:'row',height:50}}>
                            <View style={styles.itemHeaderLeft}>
                                <FontAwesome name={'image'} size={20} style={{color: FONT_COLOR_SUB_TITLE,marginLeft: 15,marginRight: 15}}/>
                                <Text style={styles.itemHeaderLeftText}>
                                    图片说明
                                </Text>
                            </View>
                            <View style={styles.itemHeaderRight}>
                                <View style={styles.itemHeaderRightBox}>
                                    <Text style={styles.itemHeaderRightText}>
                                        添加
                                    </Text>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>

                    <DividingLineViewComponent lineHeight={10}/>

                    <View style={{flexDirection:'row',height:50}}>
                        <View style={styles.itemHeaderLeft}>
                            <FontAwesome name={'pencil'} size={20} style={{color: FONT_COLOR_SUB_TITLE,marginLeft: 15,marginRight: 15}}/>
                            <Text style={styles.itemHeaderLeftText}>
                                备注
                            </Text>
                        </View>
                    </View>
                    <View style={{flexDirection:'row'}}>
                        <View style={{marginLeft: 50,marginRight: 50, height: 120}}>
                            <TextInput
                                placeholder={'继续补充酒水、遗留物信息，记录客房异常或损坏...'}
                                multiline={true}
                                maxLength={100}
                                style={{
                                    fontSize: 16,
                                    padding: 0,
                                    height:120,
                                    textAlignVertical: "top",
                                    lineHeight:25,
                                }}
                                underlineColorAndroid={'transparent'}
                                onChangeText={text => {
                                    if(text.length>100){
                                        text = text.substring(0,100)
                                    }
                                    this.setState({
                                        remark:text,
                                    })
                                }}
                            />
                        </View>
                    </View>


                    {/*选择*/}
                    <Modal
                        visible={this.state.changeNumModal}
                        //显示是的动画默认none
                        //从下面向上滑动slide
                        //慢慢显示fade
                        animationType = {'none'}
                        //是否透明默认是不透明 false
                        transparent = {true}
                        //关闭时调用
                        onRequestClose={()=> this.onRequestClose()}
                    >
                        <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                            this.onRequestClose();
                        }}>
                            <View style={styles.modalContainer}>
                                <View style={styles.modalBox} >
                                    <TouchableOpacity activeOpacity={1} onPress={()=>{
                                    }}>
                                        <View style={styles.modalTitle}>
                                            <Text style={styles.modalTitleTextNum}>
                                                选择消耗数量
                                            </Text>
                                        </View>
                                        <View style={styles.modalCenter}>
                                            <AntDesign name={'minuscircle'} onPress={()=>{
                                                let json = this.state.selectedItem;
                                                json.num = Number(json.num)-1;
                                                this.setState({
                                                    selectedItem : json,
                                                })
                                            }} size={25} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                            <TextInput style={styles.modalInput}
                                                       keyboardType='numeric'
                                                       textAlign='center'
                                                       onChangeText={text => {
                                                           this.state.selectedItem.num = Number(text)
                                                       }}
                                                       defaultValue ={this.state.selectedItem.num.toString()}
                                            />
                                            <AntDesign name={'pluscircle'} onPress={()=>{
                                                let json = this.state.selectedItem;
                                                json.num = Number(json.num)+1;
                                                this.setState({
                                                    selectedItem : json,
                                                })
                                            }} size={25} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                        </View>
                                        <View style={styles.modalBottom}>
                                            <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                                this.setState({
                                                    changeNumModal:false,
                                                })
                                            }}>
                                                <View style={styles.modalBottomLeft}>
                                                    <Text style={styles.modalBottomLeftText}>
                                                        取消
                                                    </Text>
                                                </View>
                                            </TouchableOpacity>
                                            <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                                let json = this.state.selectedItem;
                                                let consume = this.state.consume;
                                                if(Number(json.num)===0){
                                                    delete consume[json.code];
                                                }else{
                                                    consume[json.code]['num'] = json.num;
                                                }
                                                this.setState({
                                                    consume : consume,
                                                    changeNumModal:false,
                                                })
                                            }}>
                                                <View style={styles.modalBottomRight}>
                                                    <Text style={styles.modalBottomRightText}>
                                                        确定
                                                    </Text>
                                                </View>
                                            </TouchableOpacity>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>

                </ScrollView>

            </SafeAreaView>
        )
    }

    onRequestClose(){
        this.setState({
            changeNumModal: false,
        })
    }


    _submitClick=()=>{
        let {dispatch} = this.props;

        this.setState({
            btnColor:'#cccccc'
        })
        if(this.state.btnColor==='#cccccc'){
            console.log("停止")
        }else{
            console.log("继续")
            let whsk_Order_detail_arr = [];

            if(JSON.stringify(this.state.consume)!=='{}'){
                for(let item in this.state.consume){
                    whsk_Order_detail_arr.push({"code":item,"quantity":this.state.consume[item]['num']})
                }
            }
            if(JSON.stringify(this.state.leave)!=='{}'){
                for(let item in this.state.leave){
                    whsk_Order_detail_arr.push({"code":item,"quantity":1})
                }
            }
            if(JSON.stringify(this.state.roomState)!=='{}'){
                for(let item in this.state.roomState){
                    whsk_Order_detail_arr.push({"code":item,"quantity":1})
                }
            }
            let str = {"arg":{"postgledger":"yes"},"whsk_Order_detail":whsk_Order_detail_arr,"whsk_Order":{"place":this.state.place,"parentid":this.state.orderpid,"ordertype":"查房,查遗留/异常/消费","remark":this.state.remark,}};
            let whsk_Order_picture = [];
            let str3 = {"whsk_Order_picture":whsk_Order_picture};
            for (let i = 0; i < this.state.imageArr.length; i++){
                if(this.state.imageArr[i]['base64']){
                    whsk_Order_picture.push(this.state.imageArr[i]['base64'])
                }
            }
            dispatch(save_checkmsg(str,str3))
        }
    }

    _render_consume=()=>{
        // console.log(JSON.stringify(this.state.consume))
        // console.log("------"+JSON.stringify(this.state.selectedItem))
        let outHtml = [];
        for(let item in this.state.consume){
            let html = (
                <View style={[styles.itemLine,{marginTop:2}]}>
                    <View style={styles.textBox}>
                        <View style={styles.leftBox}>
                            <Text style={styles.text}>
                                {this.state.consume[item]['name']}
                            </Text>
                        </View>
                        <TouchableOpacity activeOpacity={0.9} style={styles.rightBox} onPress={()=>{
                            this.setState({
                                selectedItem:{'code':item,'name':this.state.consume[item]['name'],'num':Number(this.state.consume[item]['num'])},
                                changeNumModal : true,
                            })
                        }}>
                            <Text style={styles.numText}>
                                x{this.state.consume[item]['num']}
                            </Text>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.9} style={styles.rightBox} onPress={()=>{
                            let consume_json = this.state.consume;
                            delete consume_json[item];
                            this.setState({
                                consume : consume_json
                            })
                        }}>
                            <AntDesign name={'closecircle'} size={18} style={{color: FONT_COLOR_SUB_TITLE}}/>
                        </TouchableOpacity>
                    </View>
                </View>
            );
            outHtml.push(html)
        }
        return outHtml
    };

    _render_leave=()=>{
        // console.log(JSON.stringify(this.state.leave))
        let outHtml = [];
        for(let item in this.state.leave){
            let html = (
                <View style={[styles.itemLine,{marginTop:2}]}>
                    <View style={styles.textBox}>
                        <View style={styles.leftBox}>
                            <Text style={styles.text}>
                                {this.state.leave[item]}
                            </Text>
                        </View>
                        <TouchableOpacity activeOpacity={0.9} style={styles.rightBox} onPress={()=>{
                            let leave_json = this.state.leave;
                            delete leave_json[item];
                            this.setState({
                                leave : leave_json
                            })
                        }}>
                            <AntDesign name={'closecircle'} size={18} style={{color: FONT_COLOR_SUB_TITLE}}/>
                        </TouchableOpacity>
                    </View>
                </View>
            )
            outHtml.push(html)
        }
        return outHtml
    }

    _render_roomState=()=>{
        // console.log(JSON.stringify(this.state.roomState))
        let outHtml = [];
        for(let item in this.state.roomState){
            let html = (
                <View style={[styles.itemLine,{marginTop:2}]}>
                    <View style={styles.textBox}>
                        <View style={styles.leftBox}>
                            <Text style={styles.text}>
                                {this.state.roomState[item]}
                            </Text>
                        </View>
                        <TouchableOpacity activeOpacity={0.9} style={styles.rightBox} onPress={()=>{
                            let roomState_json = this.state.roomState;
                            delete roomState_json[item];
                            this.setState({
                                roomState : roomState_json
                            })
                        }}>
                            <AntDesign name={'closecircle'} size={18} style={{color: FONT_COLOR_SUB_TITLE}}/>
                        </TouchableOpacity>
                    </View>
                </View>
            )
            outHtml.push(html)
        }
        return outHtml
    }

}

const props = state => {
    return {
        onCheckUnusual:state.onCheckUnusual,
    }
}

export default addCheckUnusualScreen = connect(props)(addCheckUnusualScreen);
